package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.PageBean;
import com.itheima.dto.ClazzQueryDto;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.service.ClazzService;
import com.itheima.vo.ClazzVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean pageQuery(ClazzQueryDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<ClazzVo> page = clazzMapper.query(dto);
        long total = page.getTotal();
        List<ClazzVo> list = page.getResult();
        PageBean pageBean = new PageBean(total, list);
        return pageBean;
    }

    @Override
    public void delete(Integer id) {
        Integer count = studentMapper.countByClazzId(id);
        if (count > 0) {
            //抛异常
            throw new RuntimeException("对不起, 该班级下有学生, 不能直接删除");
        }
        clazzMapper.delete(id);
    }

    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> findAll() {
        List<Clazz> list = clazzMapper.findAll();
        return list;
    }


}
